import {defineStore} from 'pinia'
import type {RouteRecordRaw} from 'vue-router'
import type {tokenData,loginPam,userInfoData} from '@/api/user'
import userInfoApi from '@/api/user'
import {staticRoutes,allAsyncRoutes, anyRoutes} from '@/router/routes'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
// 限定state类型
type  userInfoState = {
  token:string,
  userInfo:userInfoData,
  menuRoutes:Array<RouteRecordRaw>
}

// 过滤函数,两个参数，异步路由和名字
function filterAllAsyncRoutes(allAsyncRoutes:RouteRecordRaw[],RoutesNames:string[]){
  return allAsyncRoutes.filter(item=>{
    // 如果获取的路由名字里包含异步路由名字就过滤出来，不过仅仅是一级路由
    if(RoutesNames.includes(item.name as string)){
      //再去过滤二级
      if(item.children&&item.children.length){
       item.children = filterAllAsyncRoutes(item.children,RoutesNames)
      }
       // 找到就返回true
    return true
    }
   
  })
}

// 封装添加异步函数,参数是所有要添加的路由,遍历添加
function addAsyncRoutes(asyncAndAnyRoutes:RouteRecordRaw[]){
  // 引入router，调用添加函数
  asyncAndAnyRoutes.forEach(item=>{
    router.addRoute(item)
  })
  
}

// 封装重置路由
function resetRoutes(){
  let AllRoutes = router.getRoutes()
  AllRoutes.forEach(item=>{
    router.removeRoute(item.name as string)
  })
  addAsyncRoutes(staticRoutes)
}
export const useUserInfoStore = defineStore('userInfo',{
  state:():userInfoState=>{
    return {
      // 首次先去local中获取token，没有就空
      token: localStorage.getItem('token_key') ||'',
      userInfo:{
        routes:[],
        buttons: [],
        roles: [],
        name: '',
        avatar: ''
      },
      menuRoutes:staticRoutes
    }
  },

  actions:{
    // 登录
    async login(login:loginPam){
      try{
        const result = await userInfoApi.userInfoLogin(login)
        this.token = result.token
        // 本地还要存储一份，在返回成功的状态
        localStorage.setItem('token_key',result.token)
        return 'ok'
      }catch(error){
        return Promise.reject('登录失败')
      }
    },
    //获取用户信息
    async getUserInfo(){
      try{
        const result = await userInfoApi.getUserInfo()
          this.userInfo = result
          // 获取routes名字，过滤要添加的路由，
          let RoutesNames = result.routes
          let filterAsyncRoutes = filterAllAsyncRoutes(cloneDeep(allAsyncRoutes),RoutesNames)
          // 再添加过滤出的路由和异步路由
          addAsyncRoutes(filterAsyncRoutes.concat(anyRoutes))
          // 这样路由能跳转但是无法显示，要给menuRoutes赋值 把静态的，过滤出异步的，任意的都添加上
          this.menuRoutes = staticRoutes.concat(filterAsyncRoutes,anyRoutes)
          return 'ok'
      }
      catch(error){
        return Promise.reject('获取用户信息失败')
      }
    },
    // 清空重置单独写一个
     reset(){
      this.token = '',
      localStorage.removeItem('token_key'),
      // this.userInfo = {}
      Object.assign(this.userInfo,{
        routes:[],
        buttons: [],
        roles: [],
        name: '',
        avatar: ''
      })
    },
    // 退出是要清空token和用户信息，local中也要清掉
    async logout(){
      try{
        await userInfoApi.userInfoLogout()
        resetRoutes()
        this.reset()
        return 'ok'
      }catch(error){
        return Promise.reject('退出登录失败')
      }
    }
  },
  getters:{}
})























// import { defineStore } from 'pinia';
// import { getToken, removeToken, setToken } from '../utils/token-utils';
// import type { UserInfoState } from './interface';
// import {ElMessage} from 'element-plus'
// import {staticRoutes} from '@/router/routes'


// /**
//  * 用户信息
//  * @methods setUserInfos 设置用户信息
//  */
// export const useUserInfoStore = defineStore('userInfo', {

// 	state: (): UserInfoState => ({
//     token: getToken() as string,
//     name: '',
//     avatar: '',
//     menuRoutes: []
//   }),

// 	actions: {
//     login (username: string, password: string) {
//       return new Promise((resolve, reject) => {
//         setTimeout(() => {
//           if (username==='admin' && password==='111111') {
//             const token = 'token-atguigu'
//             setToken(token)
//             this.token = token
//             resolve(token)
//           } else {
//             reject(new Error('用户名或密码错误!'))
//             ElMessage.error('用户名或密码错误!')
//           }
//         }, 1000)
//       })
//     },

//     getInfo () {
//       return new Promise((resolve, reject) => {
//         setTimeout(() => {
//           this.name = 'admin'
//           this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
//           this.menuRoutes = staticRoutes
//           resolve({name: this.name, avatar: this.avatar, token: this.token})
//         }, 1000)
//       })
//     },

//     reset () {
//       // 删除local中保存的token
//       removeToken()
//       // 提交重置用户信息的mutation
//       this.token = ''
//       this.name = ''
//       this.avatar = ''
//     },
// 	},
// });
